<?php

namespace app\controller\adminapi\platform\app;

use app\common\model\open\OpenTemplate;
use app\controller\adminapi\platform\PlatformController;
use hiduoke\services\wechatMinApp\WechatMinAppServer;
use think\App;

class WechatOpen extends PlatformController
{
    /**
     * @var \EasyWeChat\OpenPlatform\Application|null
     */
    public $OpenApi = null;

    /**
     * @var WechatMinAppServer
     */
    public $Wx;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->platform_app_id = input('platform_app_id', 0);
        // 获取微信小程序服务对象
        $this->Wx = new WechatMinAppServer($this->platform_app_id);
        $this->OpenApi = $this->Wx->getOpenApi();
    }

    /**
     * 获取小程序模板信息
     * Create by :  刘泓宾<514660094@qq.com>
     */
    public function getOpenTemplate()
    {
        $open_template = $this->Wx->open_template;
        return $this->success('', $open_template);
    }

    /**
     * 获取预授权地址
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/ticket-token/getPreAuthCode.html
     * @return \think\response\Json
     */
    public function getPreAuthorizationUrl()
    {
        $callbackUrl = request()->domain() . "/wxmin/open/callback?appid=" . $this->platform_app_id;
        $res = $this->OpenApi->getPreAuthorizationUrl($callbackUrl);
        return $this->success('', $res);
    }

    /**
     * 获取授权账号详情
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/authorization-management/getAuthorizerInfo.html
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function getWechatAppInfo()
    {
        $platform_app = $this->Wx->getPlatformApp();
        $res = $this->OpenApi->getAuthorizer($platform_app['appid']);
        return $this->success('', $res);
    }

    //region 小程序代码管理

    /**
     * 上传代码并生成体验版
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/commit.html
     * @param $version string 版本号
     * @param $desc string 版本描述
     * @return \think\response\Json
     */
    public function commit($version = "1.0.0", $desc = '版本提交')
    {
        $open_template = $this->Wx->open_template;
        $platform_app = $this->Wx->getPlatformApp();
        // 配置文件
        $extJson = json_encode([
            'extEnable' => true,
            "extAppid"  => $platform_app['appid'],
            'ext'       => [
                'baseUrl'             => request()->domain(),
                'plaid'               => $this->Wx->plaid,
                'platform_appid'      => $this->Wx->platform_app_id,
                'addon_name'          => $this->Wx->addon_name,
                'authorization_appid' => $this->Wx->authorization_appid
            ]
        ]);
        $res = $this->Wx->miniProgram()->code->commit($open_template['template_id'], $extJson, $version, $desc);
        if ($res['errcode'] == 0) {
            return $this->success($res['errmsg']);
        } else {
            return $this->error($res['errmsg'], $res);
        }
    }

    /**
     * 获取已上传的代码页面列表
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/getCodePage.html
     * @return \think\response\Json
     */
    public function getCodePage()
    {
        $res = $this->Wx->miniProgram()->code->getPage();
        if ($res['errcode'] == 0) {
            return $this->success('', $res['page_list']);
        } else {
            return $this->error($res['errmsg'], $res);
        }
    }

    /**
     * 获取体验二维码
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/getTrialQRCode.html
     * @return \think\response\Json
     */
    public function getTrialQRCode($path = "")
    {
        $res = $this->Wx->miniProgram()->code->getQrCode(urlencode($path));
        return $this->success('', 'data:image/png;base64,' . base64_encode($res));
    }

    /**
     * 提交代码审核
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/submitAudit.html
     * @param $version_desc
     * @return \think\response\Json
     */
    public function submitAudit($version_desc = '测试审核')
    {
        $data = [
            'item_list'    => [],
            'version_desc' => $version_desc,
        ];
        $res = $this->Wx->miniProgram()->code->submitAudit($data);
        if ($res['errcode'] == 0) {
            $other_data = $this->Wx->getPlatformApp()->other_data;
            // 设置审核id
            $other_data['auditid'] = $res['auditid'];
            // 设置状态为审核中
            $other_data['status'] = 'auditing';
            $this->Wx->getPlatformApp()->save([
                'other_data' => $other_data
            ]);
        }
        return $this->success("ok", $res);
    }


    /**
     * 查询审核单状态
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/getAuditStatus.html
     * @return \think\response\Json
     */
    public function getAuditStatus()
    {
        $res = $this->Wx->miniProgram()->code->getAuditStatus($this->Wx->getPlatformApp()['other_data']['auditid']);
//0	审核成功
//1	审核被拒绝
//2	审核中
//3	已撤回
//4	审核延后
        // {
        //  "errcode": 0,
        //  "errmsg": "ok",
        //  "status": 0

//        "errcode": 0,
//  "errmsg": "ok",
//  "status": 1,
//  "reason": "账号信息不合规范",
//  "screenshot": "xxx|yyy|zzz"
        //}
        return $this->success('ok', $res);
    }

    /**
     * 撤回代码审核
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/undoAudit.html
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function undoAudit()
    {
        $res = $this->Wx->miniProgram()->code->withdrawAudit();
        return $this->success("ok", $res);
    }

    /**
     * 发布已通过审核的小程序
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/release.html
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function release()
    {
        $res = $this->Wx->miniProgram()->code->release();
        if ($res['errcode'] == 0) {
            return $this->success("ok", $res);
        } else {
            return $this->error($res['errmsg'], $res);
        }
    }

    /**
     * 版本回退
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/revertCodeRelease.html
     * @return \think\response\Json
     */
    public function revertCodeRelease()
    {
        $url = 'wxa/revertcoderelease';
        // 获取历史版本列表
        $get_history_version = input('get_history_version', 0);
        // 设置要回滚的历史版本
        $app_version = input('app_version', '');
        $query = [];
        // 获取历史版本列表
        if ($get_history_version) {
            $query = [
                'action' => 'get_history_version',
            ];
        }
        // 设置要回滚的历史版本
        if ($app_version) {
            $query = [
                'app_version' => $app_version,
            ];
        }
        $res = $this->Wx->miniProgram()->code->httpGet($url, $query);

        if ($res['errcode'] == 0) {
            return $this->success("ok", $res);
        } else {
            return $this->error($res['errmsg'], $res);
        }
    }

    /**
     * 设置小程序服务状态
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/setVisitStatus.html
     * @param $action string 可访问状态 close|open
     * @return \think\response\Json
     */
    public function setVisitStatus()
    {
        $action = input('app_action', 'close');
        $res = $this->Wx->miniProgram()->code->changeVisitStatus($action);
        if ($res['errcode'] == 0) {
            return $this->success("ok", $res);
        } else {
            return $this->error($res['errmsg'], $res);
        }
    }

    /**
     * 查询小程序服务状态
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/getVisitStatus.html
     * @return \think\response\Json
     */
    public function getVisitStatus()
    {
        $res = $this->Wx->miniProgram()->code->httpPostJson("wxa/getvisitstatus", []);
        if ($res['errcode'] != 0) {
            return $this->error($res['errmsg']);
        }
        return $this->success("ok", $res);
    }

    /**
     * 分阶段发布
     * TODO前端未使用
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/grayRelease.html
     * @param $grayPercentage int 灰度百分比 0-100
     * @return \think\response\Json
     */
    public function grayRelease($grayPercentage = 50)
    {
        $res = $this->Wx->miniProgram()->code->grayRelease($grayPercentage);
        return $this->success("ok", $res);
    }

    /**
     * 获取分阶段发布详情
     * TODO前端未使用
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/getGrayReleasePlan.html
     * @return \think\response\Json
     */
    public function getGrayReleasePlan()
    {
        $res = $this->Wx->miniProgram()->code->getGrayRelease();
        return $this->success("ok", $res);
    }

    /**
     * 取消分阶段发布
     * TODO前端未使用
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/revertGrayRelease.html
     * @return \think\response\Json
     */
    public function revertGrayRelease()
    {
        $res = $this->Wx->miniProgram()->code->revertGrayRelease();
        return $this->success("ok", $res);
    }


    /**
     * 查询各版本用户占比
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/getSupportVersion.html
     * @return \think\response\Json
     */
    public function getSupportVersion()
    {
        $res = $this->Wx->miniProgram()->code->getSupportVersion();
        return $this->success("ok", $res);
    }

    /**
     * 设置最低基础库版本
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/setSupportVersion.html
     * @return \think\response\Json
     */
    public function setSupportVersion($version)
    {
        $res = $this->Wx->miniProgram()->code->setSupportVersion($version);
        return $this->success("ok", $res);
    }

    /**
     * 查询服务商审核额度
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/setCodeAuditQuota.html
     * @return \think\response\Json
     */
    public function setCodeAuditQuota()
    {
        $res = $this->Wx->miniProgram()->code->queryQuota();
        //{
        //    "errcode": 0,
        //    "errmsg": "ok",
        //    "rest": 99,
        //    "limit": 100,
        //    "speedup_rest": 0,
        //    "speedup_limit": 0
        //}
        return $this->success("ok", $res);
    }

    /**
     * 加急代码审核
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/speedupCodeAudit.html
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function speedupCodeAudit()
    {
        // 这个可以设置为管理员可用
        $res = $this->Wx->miniProgram()->code->speedupAudit($this->Wx->getPlatformApp()['other_data']['auditid']);
        return $this->success("ok", $res);
    }

    /**
     * 查询小程序版本信息
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/getVersionInfo.html
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function getVersionInfo()
    {
        $res = $this->Wx->miniProgram()->code->httpPostJson("wxa/getversioninfo", []);

        if ($res['errcode'] == 0) {
            return $this->success("ok", $res);
        } else {
            return $this->error($res['errmsg'], $res);
        }

//        $data = [
//            'errcode'      => 0,
//            'errmsg'       => 'ok',
//            'exp_info'     => [
//                'exp_time'    => 1640762988,
//                'exp_version' => 'V1.0',
//                'exp_desc'    => 'test'
//            ],
//            'release_info' => [
//                'release_time'    => 1640763902,
//                'release_version' => 'V1.5',
//                'release_desc'    => 'test'
//            ]
//        ];
//
//        return $this->success("ok", $data);
    }

    /**
     * 查询最新一次审核单状态
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/getLatestAuditStatus.html
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function getLatestAuditStatus()
    {
        $res = $this->Wx->miniProgram()->code->getLatestAuditStatus();
        if ($res['errcode'] == 0) {
            return $this->success("ok", $res);
        } else {
            return $this->error($res['errmsg'], $res);
        }
    }

    /**
     * 上传提审素材
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/uploadMediaToCodeAudit.html
     * Create by :  刘泓宾<514660094@qq.com>
     * @return void
     */
    public function uploadMediaToCodeAudit()
    {
        // TODO 未实现
    }

    /**
     * 获取隐私接口检测结果
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/code-management/getCodePrivacyInfo.html
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function getCodePrivacyInfo()
    {
        $res = $this->Wx->miniProgram()->code->httpGet('/wxa/security/get_code_privacy_info');
        return $this->success("ok", $res);
    }

    //endregion

    //region 隐私协议

    /**
     * 配置小程序隐私设置
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/privacy-management/setPrivacySetting.html
     * @return \think\response\Json
     */
    public function setPrivacySetting($owner_setting = [], $setting_list = [])
    {
        $params = [
            'owner_setting'         => $owner_setting,
            'setting_list'          => $setting_list,
            'sdk_privacy_info_list' => []
        ];
        $res = $this->Wx->miniProgram()->privacy->set($params);

        if ($res['errcode'] == 0) {
            return $this->success("ok", $res);
        } else {
            return $this->error($res['errmsg'], $res);
        }
    }

    /**
     * 查询小程序隐私设置
     * Create by :  刘泓宾<514660094@qq.com>
     * @document https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/miniprogram-management/privacy-management/getPrivacySetting.html
     * @return \think\response\Json
     */
    public function getPrivacySetting($privacy_ver = 1)
    {
        $data = ['privacy_ver' => $privacy_ver];
        $res = $this->Wx->miniProgram()->privacy->httpPostJson('cgi-bin/component/getprivacysetting', $data);
        if ($res['errcode'] == 0) {
            return $this->success("ok", $res);
        } else {
            return $this->error($res['errmsg'], $res);
        }
    }
    //endregion
}
